<?php
require_once("../common/db.php");

//接收需要添加的参数
$menu_id 	 = $_POST['menuId'];
$name    	 = $_POST['interfaceName'];
$path    	 = $_POST['interfaceAddress'];
$description = $_POST['interfaceDesc'];
$method      = $_POST['methodValue'];
$result      = $_POST['resultValue'];
$restfulArr  = isset($_POST['restfulArr'])==false?[]:$_POST['restfulArr'];
$bodyArr     = isset($_POST['bodyArr'])==false?[]:$_POST['bodyArr'];

//添加接口菜单
$sql = "insert into interface_menu values(NULL,'{$name}',{$menu_id},'{$path}')";
//执行SQL
$dbResult = $db->query($sql);
if(!$dbResult){
	echo json_encode(array("success"=>false,"message"=>"接口信息添加失败"));
    exit();
}

//获取接口菜单ID
$menuId = mysqli_insert_id($db);

//创建添加接口信息所需接口语句
$sql = "insert into interface_detail values(NULL,{$menuId},'{$name}','{$path}','{$description}','{$method}','{$result}')"; 

//执行SQL
$dbResult = $db->query($sql);
if(!$dbResult){
	echo json_encode(array("success"=>false,"message"=>"接口信息添加失败"));
    exit();
}

//获取上条信息添加的ID
$interfaceId = mysqli_insert_id($db);
if(!$interfaceId){
	echo json_encode(array("success"=>false,"message"=>"接口信息添加失败"));
    exit();
}

//为当前接口添加参数信息
$insertSql = "";
if(count($restfulArr)>0){

   //创建SQL语句	
   for($i=0;$i<count($restfulArr);$i++){
   	   $insertSql.= "(NULL,{$interfaceId},'{$restfulArr[$i]['isMust']}','{$restfulArr[$i]['paramsName']}','{$restfulArr[$i]['paramsType']}','{$restfulArr[$i]['paramsDesc']}','RESTFUL'),";
   }	

   
}

if(count($bodyArr)>0){
	
   //创建SQL语句	
   for($i=0;$i<count($bodyArr);$i++){
   	   $insertSql.= "(NULL,{$interfaceId},'{$bodyArr[$i]['isMust']}','{$bodyArr[$i]['paramsName']}','{$bodyArr[$i]['paramsType']}','{$bodyArr[$i]['paramsDesc']}','BODY'),";
   }	
}


//去除最后的字符
$insertSql = rtrim($insertSql,",");
if(!empty($insertSql)){

	//执行添加语句
	$dbResult = $db->query("insert into interface_params values".$insertSql);
	if(!$dbResult){

		//手动回滚操作，删除刚才添加的接口信息
		$removeSql = "delete from interface_detail where id = {$menu_id}";
		$db->query($removeSql);
		   
		echo json_encode(array("success"=>false,"message"=>"接口参数添加失败"));
	    exit();
	}
}

echo json_encode(array("success"=>true));

//断开连接
mysqli_close($db);
